import React from "react"
import { Color } from "../model/color"

interface Props {
    color: Color;
    // 绑定 父组件的 setColor
    onColorUpdated: (color: Color) => void;
}

// 高阶函数
const updateColor =
    (props: Props, colorId: keyof Color) =>
        (value: any) => {
            props.onColorUpdated({
                // 展开 接口,单一改变颜色
                ...props.color,
                [colorId]: value
            })
        }

const ColorPicker: React.FC<Props> = (props) => {
    // updateColor("red")
    return (
        <div>
            <ColorSliderComponents
                value={props.color.red}
                onValueUpdated={updateColor(props, "red")}
            />
            <br />
            <ColorSliderComponents
                value={props.color.green}
                onValueUpdated={updateColor(props, "green")}
            />
            <br />
            <ColorSliderComponents
                value={props.color.blue}
                onValueUpdated={updateColor(props, "blue")}
            />
        </div>
    )
}

interface PropsColorSlider {
    value: number;
    onValueUpdated: (newValue: number) => void;
}

const ColorSliderComponents: React.FC<PropsColorSlider> = (props) => {
    return (
        <div>
            <input
                type="range"
                min="0"
                max="255"
                value={props.value}
                onChange={(event) => props.onValueUpdated(+event.target.value)}
            />
            {props.value}
        </div>
    )
}

export default ColorPicker